<template>
    <div style="max-height: 400px;overflow-y: auto;">
        <div v-if="imageList.length>0" style="display: flex;flex-wrap: wrap;justify-content: space-between;">
            <div v-for="(item, index) in imageList" :key="index" style="width: 18%;margin-bottom: 20px;">
                <div style="display: flex;flex-direction: column;align-items: center;">
                    <div style="cursor: pointer;;padding: 2px;border: 6px solid #ccc;display: flex;align-items: center;">
                        <el-image style="width: 140px;height: 150px;" :src="item.url" :preview-src-list="srcList" />
                    </div>
                    <div style="margin-top: 8px;text-align: center;">{{ item.name }}</div>
                </div>
            </div>
            <div v-for="items in adaptation" style="width: 18%;" />
        </div>
        <el-empty description="暂无数据" v-if="imageList.length===0"></el-empty>
        <pagination v-if="pageParam.total > 10" :total="pageParam.total" :page.sync="pageParam.pageNum"
            :limit.sync="pageParam.pageSize" @pagination="doSearch" />
    </div>
</template>

<script>
import SysConst from '@/common/const'
// import JSZip from 'jszip';
import {
    getPrjFileInfoApi,
    downloadApi_New,
    batchDownloadApi
} from '@/api/attachmentInfo'
export default {
    name: 'PicturePage',
    props: {
        pictureShow: {
            type: Boolean,
            default: false
        },
        prjParams: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            adaptation: [],
            imageList: [
            ],
            tableData: [],
            srcList: [],
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: 12 // 总数
            },
            loading: false,
            downIndex: 0
        }
    },
    watch: {
        pictureShow: {
            async handler(val) {
                if (val) {
                    await this.doSearch()
                }
            }, deep: true, immediate: true
        }
    },
    methods: {
        // 获取图片的路径
        getImagePath(item) {
            return item.filePath + item.forntFilePath
        },
        getBase64(data) {
            return new Promise((resolve, reject) => {
                const blob = new Blob([data], { type: 'image/jpg' }) // 必须指定type类型
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = () => resolve(reader.result)
                reader.onerror = (error) => reject(error)
            })
        },
        async changeImageList() {
            this.loading = this.$loading({
                lock: true,
                text: '正在处理,请稍后...',
                spinner: 'el-icon-loading',
                fullscreen: true
            })
            for (let i = 0; i < this.tableData.length; i++) {
                // this.downIndex++
                const params = {
                    fileId: this.tableData[i].fileId,
                    fileName: this.tableData[i].fileName
                }
                const { data } = await downloadApi_New(params)
                const imgaes = await this.getBase64(data)
                const listObj = {
                    url: imgaes,
                    name: this.tableData[i].fileName
                }
                this.srcList.push(imgaes)
                this.imageList = [...this.imageList, listObj]
                this.adaptation = this.findNextDivisibleByFive(this.imageList.length)
                this.loading.close()
            }
        },
        findNextDivisibleByFive(num) {
            if (num % 5 === 0) {
                return num
            } else {
                return Math.ceil(num / 5) * 5
            }
        },
        async doSearch(item) {
            this.tableData = []
            this.imageList = []
            const params = {
                prjId: this.$route.query.prjId,
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                ...this.prjParams,
                pictureFormat: "01",
            }
            const { code, data } = await getPrjFileInfoApi(params)
            this.pageParam.total = data?.total || SysConst.TOTAL
            this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
            this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
            if (+code === 200&&data.records.length>0) {
                this.tableData = data.records
                await this.changeImageList()
                // await this.changeFileFormat()
            }
        },
        // arrayBufferToBase64(buffer, mimeType = 'image/jpeg') {
        //     // 创建一个 Uint8Array 视图来访问 ArrayBuffer 的内容
        //     const array = new Uint8Array(buffer);
        //     // 使用 TextEncoder 或者 String.fromCharCode 将 Uint8Array 转换为字符串
        //     // 注意：TextEncoder 可能不在所有环境中都可用，这里使用 String.fromCharCode 作为备选方案
        //     let str = '';
        //     for (let i = 0; i < array.length; i++) {
        //         str += String.fromCharCode(array[i]);
        //     }
        //     // 使用 btoa 函数将字符串转换为 Base64 编码
        //     const base64 = btoa(str);
        //     // 构建 data URL
        //     const dataUrl = `data:${mimeType};base64,${base64}`;
        //     return dataUrl;
        // },
        // async changeFileFormat() {
        //     // 多个文件下载时的参数
        //     const batchParams = this.tableData.map(item => ({
        //         fileId: item.fileId,
        //         fileName: item.fileName
        //     }))
        //     const res = await batchDownloadApi({ fileMap: batchParams });
        //     const fileType = res.data.type;
        //     const blob = new Blob([res.data], { type: fileType });
        //     // 使用JSZip处理blob
        //     JSZip.loadAsync(blob).then(async (zip) => {
        //         // 假设你想解压ZIP中的第一个文件并将其转换为base64
        //         const files = Object.values(zip.files);
        //         if (files.length > 0) {
        //             for (let i = 0; i < files.length; i++) {
        //                 // 读取文件内容为ArrayBuffer，然后转换为base64
        //                 const decompressionFile = files[i].async('arraybuffer').then(async (content) => {
        //                     return new Promise((resolve, reject) => {
        //                         resolve(this.arrayBufferToBase64(content));
        //                     });
        //                 });
        //                 const _images = await decompressionFile
        //                 const listImagesObj = {
        //                     url: _images,
        //                     name: files[i].name
        //                 }
        //                 this.srcList.push(_images)
        //                 this.imageList = [...this.imageList, listImagesObj]
        //                 console.log(this.imageList, "解压后图片列表");
        //                 this.adaptation = this.findNextDivisibleByFive(this.imageList.length)
        //             }
        //         } else {
        //             console.log('ZIP包是空的');
        //         }
        //     }).catch((error) => {
        //         console.error('解压ZIP时出错', error);
        //     });
        // }
    }
}

</script>
<style lang="scss" scoped>
::v-deep .el-image__error {
    width: 100px;
    height: 100px;
}
</style>
